#include "stdafx.h"
#include <serialization/ioParamStructs.h>
#include <serialization/serialization.h>
#include <memory>
#include <winsock/winsock_stub.h>

void recv_stub (
    __in  std::vector<char>& in_buf,
    __out std::vector<char>& out_buf
    )
{
    try
    {
    //RECEIVE()
        Deserialize deserialize (in_buf);
        recv_in_inout recvIN;
        deserialize (recvIN);

        std::auto_ptr<char> buf(new char[recvIN.len_]);

        int ret = recv (recvIN.s_, buf.get(), recvIN.len_, recvIN.flags_ );
    //SEND
        if (ret >= 0)
        {
            recv_out_inout recvOUT( ret, buf.get(), ret, WSAGetLastError() );
            Serialize(deserialize.get_header(), recvOUT, out_buf);
        }
        else {
            recv_out_inout recvOUT( ret, buf.get(), 0, WSAGetLastError() );
            Serialize(deserialize.get_header(), recvOUT, out_buf);
        }
    }
    catch (std::exception& ex)
    {
        LOG(plog::error) << "recv_stub (memory exeption): " << ex.what();
    }
}

void recvfrom_stub (
    __in  std::vector<char>& in_buf,
    __out std::vector<char>& out_buf
    )
{
    try
    {
    //RECEIVE()
        Deserialize deserialize (in_buf);
        recvfrom_in_inout recvfromIN;
        deserialize (recvfromIN);

        std::auto_ptr<char> buf(new char[recvfromIN.len_]);
        struct sockaddr from;

        int ret = recvfrom (recvfromIN.s_, buf.get(), recvfromIN.len_,
            recvfromIN.flags_, &from, recvfromIN.fromlen_);
    //SEND
        if (ret >= 0)
        {
            recvfrom_out_inout recvfromOUT( ret, buf.get(), ret, &from,
                recvfromIN.fromlen_, WSAGetLastError() );
            Serialize(deserialize.get_header(), recvfromOUT, out_buf);
        }
        else {
            recvfrom_out_inout recvfromOUT( ret, buf.get(), 0, &from,
                recvfromIN.fromlen_, WSAGetLastError() );
            Serialize(deserialize.get_header(), recvfromOUT, out_buf);
        }
    }
    catch (std::exception& ex)
    {
        LOG(plog::error) << "recvfrom_stub (memory exeption): " << ex.what();
    }
}